// Coroutine.ts
export class Coroutine {
    public finished: boolean = false;
    public active: boolean = false;
    public removeOnComplete: boolean = true;
    public useRawDeltaTime: boolean = false;

    private stack: Generator[] = [];
    private waitTimer: number = 0;
    private ended: boolean = false;

    constructor(generator?: Generator, removeOnComplete: boolean = true) {
        this.removeOnComplete = removeOnComplete;
        if (generator) {
            this.start(generator);
        }
    }

    public start(generator: Generator): void {
        this.stack = [generator];
        this.active = true;
        this.finished = false;
        this.waitTimer = 0;
        this.ended = false;
    }

    public update(dt: number): void {
        // console.log('Coroutine update');
        if (!this.active || this.ended) return;

        // 处理等待时间
        if (this.waitTimer > 0) {
            this.waitTimer -= dt;
            return;
        }

        // 执行当前协程
        if (this.stack.length > 0) {
            const top = this.stack[this.stack.length - 1];
            const { value, done } = top.next();

            if (done) {
                this.stack.pop();
                if (this.stack.length === 0) {
                    this.active = false;
                    this.finished = true;
                }
                return;
            }

            // 处理不同类型的 yield 返回值
            if (typeof value === 'number') {
                this.waitTimer = value;
                // console.log('等待', value, '秒');
            } else if (isGenerator(value)) {
                this.stack.push(value);
            }
            // 可扩展其他类型（如自定义等待条件）
        }
    }

    public cancel(): void {
        this.active = false;
        this.finished = true;
        this.stack = [];
        this.waitTimer = 0;
        this.ended = true;
    }

    public replace(generator: Generator): void {
        this.cancel();
        this.start(generator);
    }
}

// 类型守卫：判断是否为生成器
function isGenerator(obj: any): obj is Generator {
    return obj && typeof obj.next === 'function';
}

// 等待辅助类（可选）
export class WaitForSeconds {
    constructor(public duration: number) {}
}